import { App, Button, DatePicker, Flex, Form, Input, InputNumber, Modal, Select, Space, Table, Tag } from "antd";
import { useContext, useEffect, useState } from "react";
import { useForm } from "antd/es/form/Form";
import Search from "antd/es/input/Search";
import { CONTRACT_TYPE, contract_api } from "../api/conracts";
import { project_api } from "../api/projects";
import { provider_api } from "../api/providers";
import { Global } from "../main";
import { USER_ROLE } from "../api/users";

export function Contract() {
    const [searchLoading, setSearchLoading] = useState(false)
    const [contractPage, setContractPage] = useState({ total: 0, content: [] })
    const [contractReq, setContractReq] = useState({ keyword: '', page: 1, size: 15, project_id: -1, provider_id: -1 })
    const [updateContractModalOpen, setContractProjectModalOpen] = useState(false)
    const [createContractModalOpen, setCreateContractModalOpen] = useState(false)
    const [createContractForm] = useForm();
    const [updateContractForm] = useForm();
    const { message, modal } = App.useApp();
    const [currentContract, setCurrentContract] = useState(null);

    const [allProjects, setAllProjects] = useState([]);
    const [allProviders, setAllProviders] = useState([]);

    const [projects, setProjects] = useState([]);
    const [providers, setProviders] = useState([]);
    const [selectedProject, setSelectedProject] = useState(-1);
    const [selectedProvider, setSelectedProvider] = useState(-1);
    const { role } = useContext(Global)
    const columns = [
        {
            title: '项目',
            dataIndex: 'project_name',
            key: 'project_name',
        },
        {
            title: '供应商',
            dataIndex: 'provider_name',
            key: 'provider_name',
        },
        {
            title: '合同编号',
            dataIndex: 'no',
            key: 'no',
        },
        {
            title: '附加合同',
            key: 'addition',
            render: (_, row) => (row.sub_contract === CONTRACT_TYPE.SUB ? <Tag>附加合同</Tag> : <></>)
        },
        {
            title: '主合同编号',
            key: 'parent_no',
            dataIndex: 'parent_no',
        },
        {
            title: '合同金额',
            key: 'contract_amount',
            dataIndex: 'contract_amount',
        },
        {
            title: '备注',
            key: 'remarks',
            dataIndex: 'remarks',
        },
        // {
        //     title: '签约日期',
        //     key: 'contract_date',
        //     dataIndex: 'contract_date',
        // },
        {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 150,
            render: (_, row) => (<Space size={'middle'}>
                <Button type="link" onClick={() => {
                    updateContractForm.setFieldsValue(row);
                    console.log(row)
                    setCurrentContract(row);
                    setContractProjectModalOpen(true)
                }} disabled={role === USER_ROLE.READONLY}>编辑</Button>
                <Button type="link" danger onClick={() => modal.confirm({
                    title: "删除合同",
                    content: `确认要删除合同：${row.name}吗？删除合同将删除对应合同下所有数据！`,
                    onOk: () => {
                        contract_api.deleteContract(row.id).then(() => {
                            reFreshContract();
                        }).catch(e => message.error(e))
                    },
                    okText: '确定',
                    cancelText: '取消'
                })} disabled={role === USER_ROLE.READONLY}>删除</Button>
            </Space>)
        },
    ];
    const reFreshContract = (ur) => {
        let request = contractReq;
        if (!!ur) {
            request = ur;
        }
        contract_api.pageContract(request).then(data => {
            setContractPage({ ...data, content: data.content.map(it => ({ ...it, key: it.id })) })
            setSearchLoading(false)
        }).catch(e => message.error(e))
    }

    useEffect(() => {
        reFreshContract()
        project_api.pageProject({ keyword: '', page: 1, size: -1 }).then(projects => {
            setAllProjects(projects.content.map(it => ({ label: it.name, value: it.id })))
            setProjects(projects.content.map(it => ({ label: it.name, value: it.id })))
        }).catch(e => message.error(e));
        provider_api.pageProvider({ keyword: '', page: 1, size: -1 }).then(providers => {
            setProviders(providers.content.map(it => ({ label: it.name, value: it.id })))
            setAllProviders(providers.content.map(it => ({ label: it.name, value: it.id })))
        }).catch(e => message.error(e));
    }, []);
    return <>
        <Space style={{ margin: '10px' }}>
            <Select size="large" style={{ width: '15vw' }} value={selectedProject} defaultValue={-1}
                showSearch
                title="选择项目" filterOption={
                    (input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                } options={[{ value: -1, label: '所有项目' }, ...projects]}
                onChange={(value) => {
                    setSelectedProject(value);
                    reFreshContract({ ...contractReq, project_id: value });
                }}></Select>
            <Select size="large" style={{ width: '15vw' }} value={selectedProvider} defaultValue={-1}
                showSearch
                filterOption={
                    (input, option) => {
                        return (option?.label ?? '').toLowerCase().includes(input.toLowerCase())
                    }
                }
                title="选择供应商" options={[{ value: -1, label: '所有供应商' }, ...providers]}
                onChange={(value) => {
                    setSelectedProvider(value);
                    reFreshContract({ ...contractReq, provider_id: value })
                }}></Select>
            <Search size="large" placeholder="输入合同编号进行搜素" style={{ maxWidth: '30vw' }} loading={searchLoading}
                onSearch={(value) => {
                    setSearchLoading(true)
                    setContractReq({ ...contractReq, keyword: value, project_id: selectedProject, provider_id: selectedProvider })
                    reFreshContract({ ...contractReq, keyword: value, project_id: selectedProject, provider_id: selectedProvider })
                }}></Search>
            <Button size="large" type="primary" onClick={() => {
                setCurrentContract(null)
                createContractForm.setFieldsValue(null)
                createContractForm.resetFields();
                setCreateContractModalOpen(true)
            }} disabled={role === USER_ROLE.READONLY}>创建</Button>
        </Space>
        <Table size="small" pagination={{
            position: ["bottomLeft"],
            pageSizeOptions: [contractReq.size],
            total: contractPage.total,
            current: contractReq.page,
            pageSize: contractReq.size,
            onChange: (page, pageSize) => {
                setContractReq({ ...contractReq, page: page, size: pageSize });
                reFreshContract({ ...contractReq, page: page, size: pageSize })

            }
        }} dataSource={contractPage.content} columns={columns}></Table>
        <Modal maskClosable={false} title="编辑合同" okText="确定" cancelText="取消" onOk={() => {
            updateContractForm.validateFields().then(data => {
                contract_api.updateContract(data).then(() => {
                    reFreshContract();
                    setContractProjectModalOpen(false)
                }).catch(e => {
                    message.error(e.response.data || "")
                })
            });

        }} onCancel={() => setContractProjectModalOpen(false)} open={updateContractModalOpen}>
            <Form labelCol={{ span: 6 }} value={currentContract} wrapperCol={{ span: 18 }} form={updateContractForm} initialValues={currentContract}>
                <Form.Item label="索引" name={"id"} hidden>
                    <Input />
                </Form.Item>
                <Form.Item label="项目" name={"project_id"} rules={[{
                    required: true,
                    message: '请选择项目'
                }]}>
                    <Select options={projects}>

                    </Select>
                </Form.Item>
                <Form.Item label="供应商" name={"provider_id"} rules={[{
                    required: true,
                    message: '请选择供应商'
                }]}>
                    <Select options={providers}>

                    </Select>
                </Form.Item>
                <Form.Item label="合同编号" name={"no"} rules={[{
                    required: true,
                    message: '请输入合同编号'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="主合同编号" name={"parent_no"}>
                    <Input placeholder="附加合同需填入"></Input>
                </Form.Item>
                <Form.Item label="合同金额" name={"contract_amount"} rules={[{
                    required: true,
                    message: '请输入合同金额'
                }]}>
                    <InputNumber style={{ width: '100%' }} formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value) => value.replace(/\$\s?|(,*)/g, '')} ></InputNumber>
                </Form.Item>
                <Form.Item label="备注" name={"remarks"} rules={[{max: 50}]}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
            </Form>
        </Modal>
        <Modal maskClosable={false} title="新建合同" okText="确定" cancelText="取消" onOk={() => {
            createContractForm.validateFields().then(data => {
                contract_api.createContract(data).then(() => {
                    reFreshContract();
                    setCreateContractModalOpen(false)
                }).catch(e => {
                    message.error(e.response.data || "")
                })
            });

        }} onCancel={() => setCreateContractModalOpen(false)} open={createContractModalOpen}>
            <Form labelCol={{ span: 6 }} wrapperCol={{ span: 18 }} form={createContractForm} initialValues={currentContract}>
                <Form.Item label="项目" name={"project_id"} rules={[{
                    required: true,
                    message: '请选择项目'
                }]}>
                    <Select options={projects}>

                    </Select>
                </Form.Item>
                <Form.Item label="供应商" name={"provider_id"} rules={[{
                    required: true,
                    message: '请选择供应商'
                }]}>
                    <Select options={providers}>

                    </Select>
                </Form.Item>
                <Form.Item label="合同编号" name={"no"} rules={[{
                    required: true,
                    message: '请输入合同编号'
                }]}>
                    <Input></Input>
                </Form.Item>
                <Form.Item label="主合同编号" name={"parent_no"}>
                    <Input placeholder="附加合同需填入"></Input>
                </Form.Item>
                <Form.Item label="合同金额" name={"contract_amount"} rules={[{
                    required: true,
                    message: '请输入合同金额'
                }]}>
                    <InputNumber style={{ width: '100%' }}
                        formatter={(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
                        parser={(value) => value.replace(/\$\s?|(,*)/g, '')}></InputNumber>
                </Form.Item>
                <Form.Item label="备注" name={"remarks"} rules={[{max: 50}]}>
                    <Input.TextArea></Input.TextArea>
                </Form.Item>
            </Form>
        </Modal>
    </>
}